<template>
  <el-dialog v-model="visible" title="文件统计信息" width="800px" draggable append-to-body>
    <div class="statistics-container">
      <!-- 统计卡片 -->
      <el-row :gutter="20" class="statistics-cards">
        <el-col :span="6">
          <div class="stat-card total">
            <div class="stat-icon">
              <el-icon size="40"><Files /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ statistics.totalFiles }}</div>
              <div class="stat-label">总文件数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card processed">
            <div class="stat-icon">
              <el-icon size="40"><SuccessFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ statistics.processedFiles }}</div>
              <div class="stat-label">已处理</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card failed">
            <div class="stat-icon">
              <el-icon size="40"><CircleCloseFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ statistics.failedFiles }}</div>
              <div class="stat-label">处理失败</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card pending">
            <div class="stat-icon">
              <el-icon size="40"><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ statistics.pendingFiles }}</div>
              <div class="stat-label">待处理</div>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <!-- 总容量信息 -->
      <el-row :gutter="20" class="size-info">
        <el-col :span="24">
          <div class="size-card">
            <div class="size-icon">
              <el-icon size="50"><FolderOpened /></el-icon>
            </div>
            <div class="size-content">
              <div class="size-number">{{ formatFileSize(statistics.totalSize) }}</div>
              <div class="size-label">总存储容量</div>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <!-- 处理进度 -->
      <el-row class="progress-section">
        <el-col :span="24">
          <div class="progress-card">
            <h4>处理进度</h4>
            <el-progress 
              :percentage="processedPercentage" 
              :stroke-width="20"
              text-inside
              :color="progressColor"
            />
            <div class="progress-details">
              <span>已处理: {{ statistics.processedFiles }}/{{ statistics.totalFiles }}</span>
              <span>成功率: {{ successRate }}%</span>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <!-- 时间范围选择 -->
      <el-row class="date-filter">
        <el-col :span="24">
          <div class="filter-section">
            <el-form :inline="true">
              <el-form-item label="统计时间范围:">
                <el-date-picker
                  v-model="dateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  @change="refreshStatistics"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="refreshStatistics">刷新统计</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
    
    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="exportStatistics">导出统计</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Files, SuccessFilled, CircleCloseFilled, Clock, FolderOpened } from '@element-plus/icons-vue';
import { getFileStatistics } from '@/api/modules/datainfo/statisticsData';
import type { FileStatistics } from '@/api/types/datainfo/statisticsData';

defineOptions({
  name: 'StatisticsDialog'
});

const visible = ref(false);
const loading = ref(false);
const dateRange = ref<string[]>([]);

// 统计数据
const statistics = ref<FileStatistics>({
  totalFiles: 0,
  processedFiles: 0,
  failedFiles: 0,
  pendingFiles: 0,
  totalSize: 0
});

// 计算处理进度百分比
const processedPercentage = computed(() => {
  if (statistics.value.totalFiles === 0) return 0;
  return Math.round((statistics.value.processedFiles / statistics.value.totalFiles) * 100);
});

// 计算成功率
const successRate = computed(() => {
  if (statistics.value.processedFiles === 0) return 0;
  const successFiles = statistics.value.processedFiles - statistics.value.failedFiles;
  return Math.round((successFiles / statistics.value.processedFiles) * 100);
});

// 进度条颜色
const progressColor = computed(() => {
  const percentage = processedPercentage.value;
  if (percentage < 30) return '#f56c6c';
  if (percentage < 70) return '#e6a23c';
  return '#67c23a';
});

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
  if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
};

// 获取统计数据
const fetchStatistics = async () => {
  try {
    loading.value = true;
    const params: { startDate?: string; endDate?: string } = {};
    
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0];
      params.endDate = dateRange.value[1];
    }
    
    const { data } = await getFileStatistics(params);
    statistics.value = data;
  } catch (error) {
    console.error('Fetch statistics error:', error);
    ElMessage.error('获取统计数据失败');
  } finally {
    loading.value = false;
  }
};

// 刷新统计数据
const refreshStatistics = () => {
  fetchStatistics();
};

// 导出统计数据
const exportStatistics = () => {
  try {
    const data = {
      统计时间: new Date().toLocaleString(),
      时间范围: dateRange.value.length === 2 ? `${dateRange.value[0]} 至 ${dateRange.value[1]}` : '全部',
      总文件数: statistics.value.totalFiles,
      已处理文件数: statistics.value.processedFiles,
      失败文件数: statistics.value.failedFiles,
      待处理文件数: statistics.value.pendingFiles,
      总存储容量: formatFileSize(statistics.value.totalSize),
      处理进度: `${processedPercentage.value}%`,
      成功率: `${successRate.value}%`
    };
    
    const jsonStr = JSON.stringify(data, null, 2);
    const blob = new Blob([jsonStr], { type: 'application/json' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `文件统计_${new Date().toISOString().slice(0, 10)}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('统计数据导出成功');
  } catch (error) {
    console.error('Export statistics error:', error);
    ElMessage.error('导出统计数据失败');
  }
};

// 打开对话框
const open = () => {
  visible.value = true;
  fetchStatistics();
};

// 暴露方法
defineExpose({
  open
});

// 组件挂载时获取数据
onMounted(() => {
  if (visible.value) {
    fetchStatistics();
  }
});
</script>

<style scoped lang="scss">
.statistics-container {
  padding: 20px 0;
}

.statistics-cards {
  margin-bottom: 30px;
  
  .stat-card {
    display: flex;
    align-items: center;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease;
    
    &:hover {
      transform: translateY(-5px);
    }
    
    .stat-icon {
      margin-right: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 60px;
      height: 60px;
      border-radius: 50%;
    }
    
    .stat-content {
      flex: 1;
      
      .stat-number {
        font-size: 28px;
        font-weight: bold;
        margin-bottom: 5px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #666;
      }
    }
    
    &.total {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      
      .stat-icon {
        background: rgba(255, 255, 255, 0.2);
      }
    }
    
    &.processed {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      color: white;
      
      .stat-icon {
        background: rgba(255, 255, 255, 0.2);
      }
    }
    
    &.failed {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      color: white;
      
      .stat-icon {
        background: rgba(255, 255, 255, 0.2);
      }
    }
    
    &.pending {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      color: white;
      
      .stat-icon {
        background: rgba(255, 255, 255, 0.2);
      }
    }
  }
}

.size-info {
  margin-bottom: 30px;
  
  .size-card {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 30px;
    background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
    border-radius: 12px;
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
    
    .size-icon {
      margin-right: 20px;
      color: #ff6b35;
    }
    
    .size-content {
      text-align: center;
      
      .size-number {
        font-size: 36px;
        font-weight: bold;
        color: #ff6b35;
        margin-bottom: 8px;
      }
      
      .size-label {
        font-size: 16px;
        color: #666;
      }
    }
  }
}

.progress-section {
  margin-bottom: 30px;
  
  .progress-card {
    padding: 25px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e9ecef;
    
    h4 {
      margin: 0 0 20px 0;
      color: #333;
      font-size: 18px;
    }
    
    .progress-details {
      display: flex;
      justify-content: space-between;
      margin-top: 15px;
      font-size: 14px;
      color: #666;
    }
  }
}

.date-filter {
  .filter-section {
    padding: 20px;
    background: #ffffff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    
    :deep(.el-form-item) {
      margin-bottom: 0;
    }
  }
}
</style>